import hmac
import os
import secrets
from datetime import datetime, timedelta
from hashlib import sha256

import jwt
from passlib.context import CryptContext

# 密码哈希
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")


def get_password_hash(password: str) -> str:
    return pwd_context.hash(password)


def verify_password(plain_password: str, hashed_password: str) -> bool:
    return pwd_context.verify(plain_password, hashed_password)


# JWT认证
SECRET_KEY = os.getenv("SECRET_KEY", "swift-console")
ALGORITHM = os.getenv("ALGORITHM", "HS256")
ACCESS_TOKEN_EXPIRE_MINUTES = int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", "30"))


def create_access_token(data: dict):
    to_encode = data.copy()
    expire = datetime.now() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt


def decode_access_token(token: str):
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        return payload
    except jwt.ExpiredSignatureError:
        return None
    except jwt.InvalidTokenError:
        return None


# Api签名
def generate_api_key(length=32):
    return secrets.token_urlsafe(length)


def generate_api_secret(length=64):
    return secrets.token_urlsafe(length)


def create_signature(api_key: str, api_secret: str, timestamp: str):
    message = f"{api_key}{api_secret}{timestamp}"
    return hmac.new(bytes(api_secret, 'utf-8'), message.encode('utf-8'), sha256).hexdigest()


def verify_signature(api_key: str, api_secret: str, timestamp: str, signature: str):
    message = f"{api_key}{api_secret}{timestamp}"
    secret = bytes(api_secret, 'utf-8')
    expected_signature = hmac.new(secret, message.encode('utf-8'), sha256).hexdigest()
    return hmac.compare_digest(expected_signature, signature)
